package com.example.android.activities

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.royrodriguez.transitionbutton.TransitionButton
import android.content.Intent
import android.util.Log
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.example.android.R
import com.example.android.extensions.Alert
import com.example.android.extensions.AlertBar
import com.example.android.extensions.Services
import com.example.android.utils.models.Form
import com.example.android.utils.models.MyResult
import kotlinx.coroutines.*

/**
 * @ClassName LoginActivity
 * @Author Ryan Kamanri
 * @Date 2022/6/1
 * @Description
 **/
class LoginActivity : AppCompatActivity() {

    companion object {
        const val LOGIN_KEY = "LOGIN_KEY"
    }

    private lateinit var startActivity: ActivityResultLauncher<Intent>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        RegisterActivityResults()

        InitTransitionButton()

        InitUpdatePassword()

        Alert("请先登录!")

    }

    private fun RegisterActivityResults() {

        startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            when(it.resultCode) {
                UpdatePasswordActivity.UPDATE_SUCCESS -> {
                    AlertBar {
                        it.setBackgroundColor(R.color.lime_green)
                            .setTitle("修改成功!")
                            .setText("你的密码已更新")
                    }
                }
            }
        }
    }

    private fun InitUpdatePassword() {
        findViewById<TextView>(R.id.log_in_forget_password).setOnClickListener {
            val intent = Intent(this, UpdatePasswordActivity::class.java)
            startActivity.launch(intent)

        }
    }

    private fun InitTransitionButton() {
        val transitionButton = findViewById<TransitionButton>(R.id.log_in_button)
        transitionButton.setOnClickListener {

            lifecycleScope.launch {
                kotlin.runCatching {
                    // Start the loading animation when the user tap the button
                    transitionButton.startAnimation()

                    // Do your networking task or background work here.
                    val result = LogIn()
                    delay(1000)

                    // Choose a stop animation if your call was successful or not
                    Log.d(toString(), Services.JsonUtil.ToJson(result))

                    when(result.Code) {
                        MyResult.LOG_IN_SUCCESS -> {
                            transitionButton.stopAnimation(TransitionButton.StopAnimationStyle.EXPAND) {
                                val intent = Intent(baseContext, MainActivity::class.java)
                                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                                intent.putExtra(LOGIN_KEY, LOGIN_KEY)
                                startActivity(intent)
                                finish() // Destroy this activity
                            }
                        }
                        else -> {
                            Alert("登录失败(${result.Message})")
                            transitionButton.stopAnimation(TransitionButton.StopAnimationStyle.SHAKE, null)
                        }
                    }
                }.onFailure {
                    Log.e(toString(), "Failure To Execute InitTransitionButton Caused By: ${it.message}")
                    it.printStackTrace()
                    Alert("登陆时出现错误(${it.message!!})")
                    transitionButton.stopAnimation(TransitionButton.StopAnimationStyle.SHAKE, null)

                }

            }

        }
    }

    private suspend fun LogIn(): MyResult<Form> {
        val userName = findViewById<EditText>(R.id.log_in_user_name_edit_text).text.toString()
        val password = findViewById<EditText>(R.id.log_in_password_edit_text).text.toString()

        if(userName == "") {
            return MyResult(Message = "账号不能为空")
        }
        if(password == "") {
            return MyResult(Message = "密码不能为空")
        }

        return Services.LogInService.LogIn(userName, password)
    }
}



